package util;

// Helper class for calculating time.

public class Timer {
	public static final long MINUTE_LENGTH	= 60L;
	public static final long MINUTE_HALF	= 30L;
	public static final long MINUTE_QUARTER	= 15L;
	public static final long SECOND_IN_MS	= 1000L;

	// The time in the client is always later then the time we generated the code, if the password
	// is generated at 14:56:15 or at 14:56:27, we should get the same result. This method calculates
	// the last valid time to generate the code which will be 14:56:00 for above example.
	// From xx:xx:00 till xx:xx:29 the code will always be the same, so actually the code generated
	// at 14:56:27 is the one from 14:56:00. 
	public static long getLastMomentInMinute(long minuteDivider) {
		if((MINUTE_LENGTH % minuteDivider) != 0) {
			throw new IllegalArgumentException("Can only divide a minute into full seconds");
		}

		long currentTime = getCurrentTimeInSeconds();
		currentTime -= (currentTime % minuteDivider);
		return currentTime;
	}

	public static long getCurrentTimeInSeconds() {
		return System.currentTimeMillis() / SECOND_IN_MS;
	}

	public static long getTimeLeftUntillNextMoment(long minuteDivider) {
		if((MINUTE_LENGTH % minuteDivider) != 0) {
			throw new IllegalArgumentException("Can only divide a minute into full seconds");
		}

		return minuteDivider - (getCurrentTimeInSeconds() - getLastMomentInMinute(minuteDivider));
	}
}
